package org.equinoxosgi.toast.internal.backend.emergency;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.equinoxosgi.toast.core.ICoreConstants;
import org.equinoxosgi.toast.core.LogUtility;
import org.equinoxosgi.toast.core.emergency.IEmergencyConstants;

public class EmergencyServlet extends HttpServlet {

	@Override
	protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
			throws ServletException, IOException {
		final String id = getParameter(req, resp, ICoreConstants.ID_PARAMETER);
		final int latitude = Integer.parseInt(getParameter(req, resp, IEmergencyConstants.LATITUDE_PARAMETER));
		final int longitude = Integer.parseInt(getParameter(req, resp, IEmergencyConstants.LONGITUDE_PARAMETER));
		final int heading = Integer.parseInt(getParameter(req, resp, IEmergencyConstants.HEADING_PARAMETER));
		final int speed = Integer.parseInt(getParameter(req, resp, IEmergencyConstants.SPEED_PARAMETER));
		final double lat = latitude / 100000.0;
		final double lon = longitude / 100000.0;
		LogUtility.logInfo(this,
				"Emergency: " + id + " (" + lat + "N, " + lon + "E) " + heading + "deg " + speed + "kph");
		final PrintWriter writer = resp.getWriter();
		writer.print("Help is on its way!");
		resp.setContentType(ICoreConstants.CONTENT_TYPE_PLAIN);
	}

	private String getParameter(final HttpServletRequest request, final HttpServletResponse response,
			final String parameter) throws IOException, ServletException {
		final String value = request.getParameter(parameter);
		if ((value == null) || (value.length() == 0)) {
			response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, ICoreConstants.MISSING_PARAMETER + parameter);
			throw new ServletException(ICoreConstants.MISSING_PARAMETER + parameter);
		}
		return value;
	}

}
